import { defineStore } from 'pinia'
import * as GlobalAPI from '@/api'
// import * as TransformUtils from '@/components/MarkdownPreview/transform' 

export interface BusinessState {
    writerList: any
    qa_type: any
    file_url: any
    feadId: any
}

export const useBusinessStore = defineStore('business-store', {
    state: (): BusinessState => {
        return {
            writerList: {},
            //全局报错问答类型
            qa_type: 'COMMON_QA',
            //全局保存文件问答地址
            file_url: '',
            feadId: ''
        }
    },
    actions: {
        /**
         * 更新 问答类型
         */
        update_qa_type(qa_type) {
            this.qa_type = qa_type
        },
        /**
         * 更新文件url
         */
        update_file_url(file_url) {
            this.file_url = file_url
        },
        
        update_feadId(feadId) {
            this.feadId = feadId
        },
        update_writerList(writerList) {
            this.writerList = writerList
        },
        clearWriterList() {
            this.writerList = []
        },
        /**
         * Event Stream 调用大模型python服务接口
         */
        async createAssistantWriterStylized(
            uuid,
            writerOid,
            data
        ): Promise<{
            error: number
            reader: ReadableStreamDefaultReader<string> | null
            needLogin: boolean,
            feadId: string | null  // 添加 feadId 到返回类型
        }> {
            return new Promise((resolve) => {
        
                let query_str = data.text
                let { chatId, conversationId, appId, fileUrl, fileSize, fileKey, uploadFileId, qaType, type } = data;

                // 处理后端返回结果
                const processResponse = (res) => {
                    console.log('resolve', res)
                    if (res.status === 401) {
                        //登录失效
                        return { error: 1, reader: null, needLogin: true, feadId: null }
                    } else if (res.status == 200) {
                        // 创建一个缓冲区来处理不完整的消息
                        let buffer = '';
                        
                        const reader = res.body
                            .pipeThrough(new TextDecoderStream()) // 只解码，不分割
                            .pipeThrough(
                                new TransformStream({
                                    transform: (chunk, controller) => {
                                        // 将新收到的数据块追加到缓冲区
                                        buffer += chunk;
                                        
                                        // 循环处理缓冲区中所有完整的消息
                                        while (true) {
                                            const messageEndIndex = buffer.indexOf('\n\n');
                                            
                                            // 如果在缓冲区中找不到消息分隔符，说明消息不完整，等待下一个 chunk
                                            if (messageEndIndex === -1) {
                                                break;
                                            }

                                            // 提取一条完整的消息文本
                                            const messageString = buffer.substring(0, messageEndIndex);
                                            // 从缓冲区移除已处理的消息 (包括分隔符 \n\n)
                                            buffer = buffer.substring(messageEndIndex + 2);

                                            // --- 开始解析单条完整消息 (messageString) ---
                                            if (messageString.trim() === '') continue; // 忽略空消息

                                            const lines = messageString.split('\n');
                                            let eventType = 'message';
                                            let dataPayload = '';

                                            for (const line of lines) {
                                                if (line.startsWith('event:')) {
                                                    eventType = line.substring(6).trim();
                                                } else if (line.startsWith('data:')) {
                                                    // 截取 data: 后面的所有内容
                                                    dataPayload = line.substring(5).trim();
                                                }
                                            }
                                            
                                            // --- 根据事件类型处理 ---
                                            if (eventType === 'end' && dataPayload === 'END') {
                                                console.log('Stream finished by server.');
                                                controller.terminate(); // 正常结束流
                                                return;
                                            }
                                            
                                            if (eventType === 'error') {
                                                console.error('Received error event from server:', dataPayload);
                                                // 可以选择在这里抛出错误或终止流
                                                controller.terminate();
                                                return;
                                            }

                                            if (eventType === 'message' && dataPayload) {
                                                try {
                                                    const jsonChunk = JSON.parse(dataPayload);
                                                    console.log('Parsed SSE data:', jsonChunk);

                                                    // --- 在这里放置你原来的业务逻辑 ---
                                                    localStorage.setItem('conversationId', jsonChunk.conversationId);
                                                    localStorage.setItem('chatId', jsonChunk.chatId);
                                                    localStorage.setItem('feadId', jsonChunk.feadId);
                                                    if (jsonChunk.id) { // 注意：你的JSON里似乎没有id字段，这里保留原逻辑
                                                        this.update_feadId(jsonChunk.feadId);
                                                        localStorage.setItem('feadId', jsonChunk.feadId);
                                                    }
                                                    
                                                    // 处理解析后的数据
                                                    if (jsonChunk.dataType === 't02' && jsonChunk.data) {
                                                        controller.enqueue(JSON.stringify(jsonChunk.data));
                                                        console.log('Enqueued data:', jsonChunk.data);
                                                    } else if (jsonChunk.dataType === 't11') {
                                                        controller.enqueue(JSON.stringify({ content: `问题: ${query_str}` }));
                                                    } else if (jsonChunk.dataType === 't04') {
                                                        this.writerList = jsonChunk;
                                                    }
                                                    // --- 业务逻辑结束 ---

                                                } catch (e) {
                                                    console.error('Error parsing JSON from data payload:', dataPayload, e);
                                                    // 此处可以选择忽略错误的JSON块或终止流
                                                }
                                            }
                                        }
                                    },
                                    flush: (controller) => {
                                        // 流结束时，确保所有资源被正确关闭
                                        console.log("Stream flushing and terminating.");
                                        controller.terminate();
                                    }
                                })
                            )
                            .getReader();

                        const feadId = this.feadId || localStorage.getItem('feadId') || null;

                        return { error: 0, reader, needLogin: false, feadId: feadId };
                    } else {
                        return { error: 1, reader: null, needLogin: false, feadId: null };
                    }
                }

                // 调用后端接口拿大模型结果
                GlobalAPI.createOllama3Stylized(query_str, chatId, conversationId, appId, fileUrl, fileSize, fileKey, uploadFileId, qaType, type)
                    .then((res) => resolve(processResponse(res)))
                    .catch((err) => {
                        console.error('Request failed:', err)
                        resolve({ error: 1, reader: null, needLogin: false, feadId: null });
                    });
            });
        }
    }
});